<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Family Manager - 家人信息管理中心</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* 基础样式 */
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --background-gradient: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', system-ui, sans-serif;
            background: var(--background-gradient);
            min-height: 100vh;
        }

        /* 容器样式 */
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 2rem;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 1rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        /* 头部样式 */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid var(--primary-color);
        }

        .header h1 {
            color: var(--primary-color);
            font-size: 2.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        /* 操作栏 */
        .action-bar {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        /* 按钮样式 */
        .btn {
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(74, 144, 226, 0.4);
        }

        /* 成员卡片 */
        .member-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
        }

        .member-card {
            background: white;
            border-radius: 1rem;
            padding: 1.5rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            position: relative;
            transition: transform 0.3s ease;
        }

        .member-card:hover {
            transform: translateY(-5px);
        }

        .member-actions {
            position: absolute;
            top: 1rem;
            right: 1rem;
            display: flex;
            gap: 0.5rem;
        }

        .action-btn {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            display: grid;
            place-items: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .edit-btn {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success-color);
        }

        .delete-btn {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger-color);
        }

        /* 表单弹窗 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            place-items: center;
            z-index: 1000;
        }

        .modal {
            background: white;
            padding: 2rem;
            border-radius: 1rem;
            width: 90%;
            max-width: 500px;
            position: relative;
            animation: modalSlide 0.3s ease;
        }

        @keyframes modalSlide {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 1rem;
                padding: 1rem;
            }

            .header h1 {
                font-size: 2rem;
            }
        }

        .search-container {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            /* 控制间距 */
        }

        .search-input {
            flex: 1;
            /* 自动扩展 */
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 0.5rem;
        }

        .search-btn {
            margin-left: auto;
            padding: 0.8rem 1.5rem;
            border: none;
            border-radius: 0.5rem;
            background: #4a90e2;
            color: white;
        }

        /* 新增表单相关样式 */
        .form-group {
            margin-bottom: 1.2rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 0.5rem;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
        }

        /* 新增必填字段标识 */
        .required::after {
            content: "*";
            color: var(--danger-color);
            margin-left: 0.3rem;
        }

        .toast {
            position: fixed;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 1rem 2rem;
            border-radius: 0.5rem;
            animation: toastSlide 0.3s ease;
        }

        @keyframes toastSlide {
            from {
                transform: translate(-50%, 100%);
                opacity: 0;
            }

            to {
                transform: translate(-50%, 0);
                opacity: 1;
            }
        }
    </style>
</head>

<body>

<div class="container">
    <!-- 头部 -->
    <div class="header">
        <h1>
            <i class="fas fa-heartbeat"></i>
            家人健康管理中心
        </h1>
        <button class="btn btn-primary" onclick="showAddForm()">
            <i class="fas fa-plus"></i>
            添加新成员
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="action-bar">
        <div class="search-container">
            <input type="text" class="search-input" placeholder="搜索家庭成员...">
            <button class="btn btn-primary search-btn">
                <i class="fas fa-search"></i>
            </button>
        </div>

    </div>

    <!-- 成员列表 -->
    <div class="member-grid" id="memberGrid">
        <!-- 动态生成的成员卡片 -->
    </div>
</div>

<!-- 添加/编辑表单弹窗 -->
<div class="modal-overlay" id="modalOverlay">
    <div class="modal">
        <h2 class="modal-title" id="modalTitle">添加新成员</h2>
        <form id="memberForm" onsubmit="handleSubmit(event)">
            <input type="hidden" id="memberId">

            <div class="form-group">
                <label class="required">身份证号</label>
                <input type="text" id="id" required>
            </div>

            <div class="form-group">
                <label class="required">姓名</label>
                <input type="text" id="name" required>
            </div>

            <div class="form-group">
                <label class="required">性别</label>
                <select id="gender" required>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>

            <div class="form-group">
                <label class="required">电话号码</label>
                <input type="text" id="phone" required>
            </div>

            <div class="form-group">
                <label class="required">出生日期</label>
                <input type="date" id="birthday" required>
            </div>

            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                <button type="submit" class="btn btn-primary" id="submitBtn">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 从Cookie中获取token
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    // 初始化
    function init() {
        fetchMembers();
        setupSearch();
    }

    function escapeHtml(unsafe) {
        return unsafe.replace(/[&<>"']/g, function (m) {
            switch (m) {
                case '&': return '&amp;';
                case '<': return '&lt;';
                case '>': return '&gt;';
                case '"': return '&quot;';
                case "'": return '&#39;';
            }
        });
    }

    // 渲染成员卡片
    function renderMembers(members) {
        console.log(members);
        const grid = $('#memberGrid');
        grid.empty();
        members.forEach(member => {
            grid.append(`
        <div class="member-card">
          <div class="member-actions">
            <button class="action-btn edit-btn" onclick="editMember('${escapeHtml(JSON.stringify(member))}')">
              <i class="fas fa-edit"></i>
            </button>
            <button class="action-btn delete-btn" onclick="deleteMember('${member.id}')">
              <i class="fas fa-trash"></i>
            </button>
          </div>
          <h3>${member.name}</h3>
          <p>年龄: ${new Date().getFullYear() - new Date(member.birthday).getFullYear()}</p>
          <p>性别: ${member.gender === '男' ? '男' : '女'}</p>
          <p>电话号码: ${member.phone}</p>
        </div>
      `);
        });
    }

    // 获取成员列表
    function fetchMembers() {
        const token = getCookie('token');
        $.ajax({
            url: 'http://localhost:8000/user/inhabitant/get',
            method: 'GET',
            dataType: 'json',
            xhrFields: { withCredentials: true },
            headers: {
                'Authorization': `${token}`
            },
            success: function (response) {
                if (response.code === 200) {
                    renderMembers(response.data);
                } else {
                    showToast('获取成员信息失败！');
                }
            },
            error: function () {
                document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                window.location.href = 'http://localhost:5173';
                showToast('请求失败，请稍后再试！');
            }
        });
    }

    // 新增状态管理变量
    let currentEditingId = null;

    // 显示添加表单
    function showAddForm() {
        currentEditingId = null;
        $('#modalOverlay').css('display', 'grid');
        $('#modalTitle').text('添加新成员');
        $('#submitBtn').text('保存');
        $('#id').val('').prop('disabled', false); // 修复.type('hidden')错误
        resetForm();
    }

    // 编辑成员
    // function editMember(member) {
    //   const token = getCookie('token');
    //   $.ajax({
    //     url: `/user/inhabitant/get/${id}`,
    //     method: 'GET',
    //     headers: {
    //       'Authorization': `Bearer ${token}`
    //     },
    //     success: function (response) {
    //       if (response.code === 0) {
    //         const member = response.data;
    //         currentEditingId = member.id;
    //         $('#modalOverlay').css('display', 'grid');
    //         $('#modalTitle').text('编辑成员信息');
    //         $('#submitBtn').text('更新');
    //
    //         // 填充表单数据
    //         $('#memberId').val(member.id);
    //         $('#name').val(member.name);
    //         $('#age').val(new Date().getFullYear() - new Date(member.birthday).getFullYear());
    //         $('#gender').val(member.gender);
    //         $('#phone').val(member.phone);
    //         $('#birthday').val(member.birthday.split('T')[0]);
    //       } else {
    //         showToast('获取成员信息失败！');
    //       }
    //     },
    //     error: function () {
    //       showToast('请求失败，请稍后再试！');
    //     }
    //   });
    // }

    function editMember(member) {
        member = JSON.parse(member);
        console.log('编辑成员:', member);
        if (!member || !member.id || !member.name || !member.birthday || !member.gender || !member.phone) {
            console.error('成员数据不完整');
            return;
        }

        currentEditingId = member.id;
        $('#modalOverlay').css('display', 'grid');
        $('#modalTitle').text('编辑成员信息');
        $('#submitBtn').text('更新');

        // 填充表单数据
        $('#id').val(member.id).prop('disabled', true); // 修复.type('hidden')错误
        $('#name').val(member.name);
        try {
            const birthYear = new Date(member.birthday).getFullYear();
            const currentYear = new Date().getFullYear();
            $('#age').val(currentYear - birthYear);
        } catch (e) {
            console.error('生日格式错误:', e);
            $('#age').val('');
        }
        $('#gender').val(member.gender);
        $('#phone').val(member.phone);
        try {
            $('#birthday').val(member.birthday.split('T')[0]);
        } catch (e) {
            console.error('日期格式错误:', e);
            $('#birthday').val('');
        }
    }



    // 关闭弹窗
    function closeModal() {
        $('#modalOverlay').css('display', 'none');
    }

    // 提交表单
    function handleSubmit(e) {
        e.preventDefault();

        const formData = {
            id: $('#id').val(), // 生成唯一ID
            name: $('#name').val().trim(),
            birthday: $('#birthday').val(),
            gender: $('#gender').val(),
            phone: $('#phone').val()
        };

        const url = currentEditingId ? `http://localhost:8000/user/inhabitant/update` : 'http://localhost:8000/user/inhabitant/save';
        const method = currentEditingId ? 'PUT' : 'POST';

        const token = getCookie('token');
        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers: {
                'Authorization': `${token}`
            },
            success: function (response) {
                if (response.code === 200) {
                    closeModal();
                    fetchMembers();
                    showToast(currentEditingId ? '更新成功！' : '添加成功！');
                } else {
                    showToast('操作失败！');
                }
            },
            error: function () {
                document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                window.location.href = 'http://localhost:5173';
                showToast('请求失败，请稍后再试！');
            }
        });
    }

    // 重置表单
    function resetForm() {
        $('#memberForm')[0].reset();
        $('#memberId').val('');
        $('#id').val('').prop('disabled', false); // 修复.type('hidden')错误
    }

    // 显示成功提示
    function showToast(message) {
        const toast = $('<div>').addClass('toast').text(message);
        $('body').append(toast);

        setTimeout(() => {
            toast.remove();
        }, 2000);
    }

    // 删除成员
    function deleteMember(id) {
        if (confirm('确定要删除该成员吗？')) {
            const token = getCookie('token');
            $.ajax({
                url: `http://localhost:8000/user/inhabitant/remove/${id}`,
                method: 'DELETE',
                headers: {
                    'Authorization': `${token}`
                },
                success: function (response) {
                    if (response.code === 200) {
                        fetchMembers();
                        showToast('删除成功！');
                    } else {
                        showToast('删除失败！');
                    }
                },
                error: function () {
                    document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    window.location.href = 'http://localhost:5173';
                    showToast('请求失败，请稍后再试！');
                }
            });
        }
    }

    // 初始化搜索功能
    function setupSearch() {
        const searchInput = $('.search-input');
        searchInput.on('input', () => {
            const keyword = searchInput.val().toLowerCase();
            // 添加搜索过滤逻辑
        });
    }

    // 页面加载时初始化
    $(document).ready(init);
</script>
</body>

</html>
